import Cookies from 'js-cookie'
/** 获取根域名 */
export function getRootDomain() {
    let parts = location.hostname.split('.')
    if (parts.length > 2) {
        // Remove the first subdomain and join the remaining parts
        parts.shift()
        return parts.join('.')
    } else {
        // The current domain is already the root domain
        return location.hostname
    }
}

type CookiesName = 'h5Token' | 'h5SelectUserType' | 'h5UserCode' | 'h5SelectOrgCode' | 'h5FromUrl' | 'h5Alias'

/** 设置用户中心 cookies */
export const setUserCenterCookies = (data: Partial<Record<CookiesName, string | undefined>>, sid: string) => {
    const nameList: CookiesName[] = ['h5Token', 'h5SelectUserType', 'h5UserCode', 'h5SelectOrgCode', 'h5FromUrl', 'h5Alias']
    const domain = getRootDomain()
    nameList.forEach((name: CookiesName) => {
        if (data[name]) {
            Cookies.set(`${name}${sid}`, data[name] as string, { domain })
        }
    })
}
